package com.zg.system.extra;

import org.apache.commons.compress.utils.IOUtils;
import org.springframework.core.io.ClassPathResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * @author Zxb
 */
@RestController
public class TmplController {

    public static final String TMPL_FOLDER_NAME = "tmpl";

    @GetMapping("/tmpl/download")
    public ResponseEntity<byte[]> downloadTmpl(String fileName) throws IOException {
        ClassPathResource cpr = new ClassPathResource(TMPL_FOLDER_NAME + File.separator + fileName);
        String downloadFileName = new String(fileName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
        byte[] fileByteArray = IOUtils.toByteArray(cpr.getInputStream());
        HttpHeaders headers = new HttpHeaders();
        headers.setContentDispositionFormData("attachment", downloadFileName);
        headers.setContentLength(fileByteArray.length);
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        return ResponseEntity.ok()
                .headers(headers)
                .body(fileByteArray);
    }
}
